const { userModels } = require("../../models"); //导入数据库操作模块dbModels.js
const jwt = require("../../lib/jwt");
const { findUser } = require("../../models/db_models/user_models");
const bcryptModule = require("../../lib/bcrypt");

//200 成功 ,300未通过token, 400功能拒绝，500服务器错误

//是否注册
// exports.isRegister = async function (req, res) {
//   let data = req.body;
//   //查询数据库是否存在该用户
//   await userModels.isRegister().then((result) => {
//     let code = 300;
//     console.log(result[0].count);
//     if (result[0].count > 0) {
//       //存在ss
//       code = 200;
//     }
//     res.send({ code: code });
//   });
// };

//管理员注册
exports.insertUser = async function (req, res) {
  try {
    let data = req.body;
    // 密码长度验证
    //查询数据库是否存在该用户
    await userModels.findUser(data.user_name).then(async (result) => {
      if (result.length > 0) {
        //存在用户返回400
        let code = 400;
        res.send({ code: code });
      } else {
        //不存在用户，加密,执行插入操作
        // 使用独立加密模块加密密码
        data.password = await bcryptModule.hashPassword(data.password);
        userModels.insertUser(data).then((result) => {
          let code = 200;
          res.send({ code: code });
        });
      }
    });
  } catch (error) {
    console.log(error);
  }
};

//管理员登录
exports.signin = async function (req, res) {
  try {
    let data = req.body;
    // 使用独立加密模块验证密码
    //查询数据库是否存在该用户
    await userModels.signin(data.email).then(async (result) => {
      const isPasswordValid = await bcryptModule.verifyPassword(
        data.password,
        result[0].password
      );
      if (isPasswordValid) {
        let token = jwt.generateToken(data.email);
        let userData = {
          id: result[0].id,
          username: result[0].user_name,
          ...{ token: token },
        };
        //存在
        let code = 200;
        res.send({ code: code, data: userData });
      } else {
        let code = 400;
        res.send({ code: code, message: "用户名或密码错误" });
      }
    });
  } catch (error) {
    console.error("登录错误:", error);
    res.send({ code: 500, message: "服务器错误" });
  }
};
